package com.cq.hd.member.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cq.hd.common.constant.Constant;
import com.cq.hd.common.enums.biz.WxMiniCodeShareTypeEnum;
import com.cq.hd.common.pagination.Page;
import com.cq.hd.common.response.Throw;
import com.cq.hd.common.utils.*;
import com.cq.hd.member.api.dto.EnterBusinessPageDto;
import com.cq.hd.member.api.dto.InviteBusinessUrlPageDto;
import com.cq.hd.member.api.dto.InviteBusinessUrlSaveDto;
import com.cq.hd.member.api.vo.EnterBusinessPageVo;
import com.cq.hd.member.api.vo.InviteBusinessUrlPageVo;
import com.cq.hd.member.config.WxConfig;
import com.cq.hd.member.mapper.TbBusinessMapper;
import com.cq.hd.member.po.TbInviteBusinessUrlPo;
import com.cq.hd.member.mapper.TbInviteBusinessUrlMapper;
import com.cq.hd.member.service.TbInviteBusinessUrlService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 邀请商家链接表 服务实现类
 * </p>
 *
 * @author mYunYu
 * @since 2023-11-19
 */
@Slf4j
@Service
public class TbInviteBusinessUrlServiceImpl extends ServiceImpl<TbInviteBusinessUrlMapper, TbInviteBusinessUrlPo> implements TbInviteBusinessUrlService {

    @Autowired
    private TbBusinessMapper businessMapper;

    @Autowired
    private WxConfig wxConfig;

    @Override
    public Long saveInviteBusinessUrl(InviteBusinessUrlSaveDto inviteBusinessUrlSaveDto) {
        String inviteName = inviteBusinessUrlSaveDto.getInviteName();
        String remark = inviteBusinessUrlSaveDto.getRemark();
        Integer activeCount = inviteBusinessUrlSaveDto.getActiveCount();
        // 链接有效期(0表示永久有效)
        Integer urlValidDay = inviteBusinessUrlSaveDto.getUrlValidDay();

        if (StringUtils.isBlank(inviteName)) {
            Throw.isBusinessException("请输入链接名称");
        }

        if (inviteName.length() > 10) {
            Throw.isBusinessException("链接名称最多输入10个字");
        }

        if (!StringUtils.isBlank(remark) && remark.length() > 50) {
            Throw.isBusinessException("备注最多输入50个字");
        }

        if (activeCount <= 0) {
            Throw.isBusinessException("活动发布次数必须大于0");
        }

        if (activeCount > 99999) {
            Throw.isBusinessException("活动发布次数不能大于99999次");
        }

        if (urlValidDay == null || urlValidDay < 0) {
            Throw.isBusinessException("链接有效期数据错误");
        }

        if (urlValidDay > 99999) {
            Throw.isBusinessException("链接有效期不能大于99999天");
        }

        // 链接名称不能一致
        Integer count = baseMapper.selectCount(new QueryWrapper<TbInviteBusinessUrlPo>().eq("del_state", 0)
                .eq("invite_name", inviteBusinessUrlSaveDto.getInviteName()));
        if (count != null && count > 0) {
            Throw.isBusinessException("链接名称已存在");
        }

        LocalDateTime now = LocalDateTime.now();

        // 计算失效时间=创建时间+链接有效期，如果是永久，则设置为2099-12-31 23:59:59
        LocalDateTime expireTime = urlValidDay == 0
                ? LocalDateUtil.toLocalDateTime("2099-12-31 23:59:59", Constant.YYYY_MM_DD_HH_MM_SS)
                : now.plusDays(urlValidDay);

        // 生成邀请码
        String inviteCode;
        do {
            inviteCode = NoUtils.getInviteBusinessCode();
            count = baseMapper.selectCount(new QueryWrapper<TbInviteBusinessUrlPo>().eq("invite_code", inviteCode));
        } while (count != null && count != 0);

        // 生成邀请商家的小程序码并上传到oss
        WxMiniCodeShareTypeEnum inviteBusinessEnum = WxMiniCodeShareTypeEnum.INVITE_BUSINESS;
        String param = inviteBusinessEnum.getName().replace("INVITE_URL_CODE", inviteCode);
        String miniImgUrl = wxConfig.getWxMiniCode(Constant.INVITE_BUSINESS_URL_PAGE, param, inviteBusinessEnum.getValue(), inviteCode);
        if (StringUtils.isBlank(miniImgUrl)) {
            log.error("生成邀请商家小程序码失败,inviteCode:{}", inviteCode);
            Throw.isBusinessException("生成邀请商家小程序码失败");
        }

        TbInviteBusinessUrlPo tbInviteBusinessUrlPo = new TbInviteBusinessUrlPo();
        BeanUtils.copyProperties(inviteBusinessUrlSaveDto, tbInviteBusinessUrlPo);
        tbInviteBusinessUrlPo.setInviteCode(inviteCode);
        tbInviteBusinessUrlPo.setExpireTime(expireTime);
        tbInviteBusinessUrlPo.setSettleSuccessCount(0);
        tbInviteBusinessUrlPo.setMiniImgUrl(miniImgUrl);
        tbInviteBusinessUrlPo.setCreateTime(now);
        int insert = baseMapper.insert(tbInviteBusinessUrlPo);
        if (insert == 0) {
            Throw.isBusinessException("保存邀请链接失败");
        }

        return tbInviteBusinessUrlPo.getId();
    }

    @Override
    public Page<InviteBusinessUrlPageVo> pageInviteBusinessUrl(InviteBusinessUrlPageDto inviteBusinessUrlPageDto) {
        String startTime = inviteBusinessUrlPageDto.getStartTime();
        String endTime = inviteBusinessUrlPageDto.getEndTime();
        // 状态：1-生效中，2-已失效
        Integer state = inviteBusinessUrlPageDto.getState();
        if (!StringUtils.isBlank(startTime) && startTime.length() != 19) {
            Throw.isBusinessException("日期格式错误");
        }
        if (!StringUtils.isBlank(endTime) && endTime.length() != 19) {
            Throw.isBusinessException("日期格式错误");
        }

        if (state != null) {
            inviteBusinessUrlPageDto.setExpireTime(LocalDateUtil.toLocalDateTimeToString(LocalDateTime.now(), Constant.YYYY_MM_DD_HH_MM_SS));
        }

        PageHelper.startPage(inviteBusinessUrlPageDto.getPageNum(), inviteBusinessUrlPageDto.getPageSize());
        List<InviteBusinessUrlPageVo> inviteBusinessUrlPageVos = baseMapper.listInviteBusinessUrlByDto(inviteBusinessUrlPageDto);
        if (!CollectionUtils.isEmpty(inviteBusinessUrlPageVos)) {
            LocalDateTime now = LocalDateTime.now();
            for (InviteBusinessUrlPageVo inviteBusinessUrlPageVo : inviteBusinessUrlPageVos) {
                LocalDateTime expireTime = inviteBusinessUrlPageVo.getExpireTime();
                if (!expireTime.isAfter(now)) {
                    // 状态：1-生效中，2-已失效
                    inviteBusinessUrlPageVo.setState(2);
                } else {
                    // 状态：1-生效中，2-已失效
                    inviteBusinessUrlPageVo.setState(1);
                }
            }
        }

        PageInfo<InviteBusinessUrlPageVo> pageInfo = new PageInfo<>(inviteBusinessUrlPageVos);
        return Page.newPageWithAllFields(pageInfo.getList(), pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getTotal(), pageInfo.getPages());
    }

    @Override
    public void deleteInviteBusinessUrl(Long id) {
        TbInviteBusinessUrlPo tbInviteBusinessUrlPo = baseMapper.selectById(id);
        if (tbInviteBusinessUrlPo == null) {
            Throw.isBusinessException("未找到邀请商家链接数据");
        }

        tbInviteBusinessUrlPo.setDelState(1);
        tbInviteBusinessUrlPo.setUpdateTime(LocalDateTime.now());
        int update = baseMapper.updateById(tbInviteBusinessUrlPo);
        if (update == 0) {
            Throw.isBusinessException("删除失败");
        }
    }

    @Override
    public Page<EnterBusinessPageVo> pageEnterBusiness(EnterBusinessPageDto enterBusinessPageDto) {
        PageHelper.startPage(enterBusinessPageDto.getPageNum(), enterBusinessPageDto.getPageSize());
        List<EnterBusinessPageVo> enterBusinessPageVos = businessMapper.listEnterBusinessByDto(enterBusinessPageDto);
        PageInfo<EnterBusinessPageVo> pageInfo = new PageInfo<>(enterBusinessPageVos);
        return Page.newPageWithAllFields(pageInfo.getList(), pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getTotal(), pageInfo.getPages());
    }

    @Override
    public InviteBusinessUrlPageVo getInviteBusinessUrlById(Long id) {
        TbInviteBusinessUrlPo tbInviteBusinessUrlPo = baseMapper.selectById(id);
        if (tbInviteBusinessUrlPo != null && tbInviteBusinessUrlPo.getDelState() == 0) {
            InviteBusinessUrlPageVo inviteBusinessUrlPageVo = new InviteBusinessUrlPageVo();
            BeanUtils.copyProperties(tbInviteBusinessUrlPo, inviteBusinessUrlPageVo);
            return inviteBusinessUrlPageVo;
        }
        return null;
    }
}
